package com.tx.admin.flow;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.tx.admin.annotation.Flow;
import com.tx.admin.annotation.RbacMapping;
import com.tx.admin.controller.po.TaskPagePo;
import com.tx.admin.controller.vo.EntityVo;
import com.tx.admin.controller.vo.PageVo;
import com.tx.admin.controller.vo.SuperVo;
import com.tx.admin.entity.rbac.RoleEntity;
import com.tx.admin.security.service.SecurityService;
import com.tx.admin.service.rbac.RoleService;

import io.swagger.annotations.ApiOperation;

public abstract class SuperFlow {


	@Autowired
	private RuntimeService runtimeService;
	
	@Autowired
	private TaskService taskService;
	
	@Autowired
	private RoleService roleService;
	
	@Autowired
	private SecurityService securityService;
	
	
	@PostMapping(value="/start")
	@ApiOperation(value="启动", notes="启动一个流程")
	public SuperVo start(){
	    // 启动并获取流程实例
		ProcessInstance  processInstance  = this.runtimeService
	    .startProcessInstanceByKey(this.getProcessDefinitionKey()); // 流程定义表的KEY字段值
		return SuperVo.newVo("流程启动成功:"+processInstance.getProcessInstanceId());
	}
	
	/**
	 * 查询任务
	 */
	@PostMapping(value="/page")
	@ApiOperation(value="查询我的任务")
	public PageVo<?> findAll(TaskPagePo<Map> params) {
		List<String> roleIds = securityService.getRoleAll().stream().map(val -> val.getId()).collect(Collectors.toList());
		List<Task> list = this.taskService
				.createTaskQuery()
				//.taskName(name)
				.taskCandidateGroupIn(roleIds)		
		//所有任务 .createTaskQuery()
		//.taskCandidateGroup()
		//指定人查询.taskAssignee(assignee)
		//候选人查询.taskAssignee(assignee)
		.list();
	
		PageVo page = new PageVo<>();
		list.stream().map(val -> {
			return	EntityVo.toMap(val);
		}).collect(Collectors.toList());
		
		return page;
	}
	
	
	@ApiOperation(value="用户审核")
	@PostMapping(value="/complete")
	public SuperVo complete(String taskId){
		taskService.complete(taskId); // 指定要完成的任务ID
		return SuperVo.newVo("完成任务");
	}
	
	
	
	private List<RoleEntity> getRole(String dataFunction){
		List<RoleEntity> roles = roleService.findByDataFunctionIdsLike(dataFunction);
		return roles;
	}
	
	
	protected abstract String getProcessDefinitionKey();
}
